package com.kavenka.zhufengfm.app.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * Created by kavenka on 2015/9/27 0027.
 */
public class ScaleBitmapUtil {
    /**
     * 针对图片数据进行缩小转化（二次采样）
     * @param data
     * @param toWidth
     * @param toHeigth
     * @return
     */
    public static Bitmap loadScaleBitmap(byte[] data,int toWidth,int toHeigth){
        Bitmap ret=null;
        //1.options用来进行解码的配置
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inJustDecodeBounds=true;//告诉解码解码器只进行大小的获取，不占内存
        BitmapFactory.decodeByteArray(data,0,data.length,options);
        //2.获取图片的大小
        int width = options.outWidth;
        int height = options.outHeight;
        //3.开始缩小图片，先设置解码器可以真实解码图片
        options.inJustDecodeBounds=false;
        options.inSampleSize=calculateInSampleSize(options,toWidth,toHeigth);
        //4.设置其他的优化策略
        options.inPurgeable=true;
        options.inPreferredConfig=Bitmap.Config.RGB_565;//降低一个像素的颜色字节数
        ret=BitmapFactory.decodeByteArray(data,0,data.length,options);
        return ret;
    }

    /**
     * 计算缩放比例
     * @param options
     * @param toWidth
     * @param toHeigth
     * @return
     */
    private static int calculateInSampleSize(BitmapFactory.Options options, int toWidth, int toHeigth) {
        int ret=1;
        int width = options.outWidth;
        int heigth = options.outHeight;
        if (width>toWidth && heigth>toHeigth){
            int halfHeigth = heigth / 2;
            int halfWidth = width / 2;
            while ((halfHeigth/ret)>toHeigth&&(halfWidth/ret)>toWidth){
                ret*=2;
            }
        }
        return ret;
    }
}
